package com.yunshipei.core.ui.client;

import com.yunshipei.core.utils.MimeTypeUtils;

import org.xwalk.core.XWalkHttpAuthHandler;
import org.xwalk.core.XWalkView;
import org.xwalk.core.XWalkWebResourceRequest;
import org.xwalk.core.XWalkWebResourceResponse;

import java.io.InputStream;

public final class PCModeEnterWebViewClient extends EnterWebViewClient {

    public PCModeEnterWebViewClient(XWalkView view, OnEnterWebViewClientInteractionListener enterWebViewClientInteractionListener) {
        super(view, enterWebViewClientInteractionListener);
    }

    @Override
    public boolean shouldOverrideUrlLoading(XWalkView view, String url) {
        if (mEnterWebViewClientInteractionListener != null) {
            mEnterWebViewClientInteractionListener.onWebViewUrlChanged(url);
        }
        return super.shouldOverrideUrlLoading(view, url);
    }

    @Override
    public XWalkWebResourceResponse shouldInterceptLoadRequest(XWalkView view, XWalkWebResourceRequest request) {
        String url = request.getUrl().toString();
        if (url.endsWith("_init.js")) {
            String type = MimeTypeUtils.getMimeType(view.getContext(),url);
            InputStream is = null;
            try {
                is = view.getContext().getAssets().open("empty");
                return super.createXWalkWebResourceResponse(type, ENCODING, is);
            } catch (Exception ignored) {
            }
        }
        return super.shouldInterceptLoadRequest(view, request);
    }

    @Override
    public void onReceivedHttpAuthRequest(XWalkView view, XWalkHttpAuthHandler handler, String host, String realm) {
        super.onReceivedHttpAuthRequest(view, handler, host, realm);
        handler.proceed("","");
    }
}